/**
 * 
 */
package vanhoc.android.medialcool.helper;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.blinkenlights.jid3.ID3Exception;
import org.blinkenlights.jid3.ID3Tag;
import org.blinkenlights.jid3.MP3File;
import org.blinkenlights.jid3.MediaFile;
import org.blinkenlights.jid3.v1.ID3V1Tag;
import org.blinkenlights.jid3.v1.ID3V1_0Tag;
import org.blinkenlights.jid3.v2.ID3V2_3_0Tag;
import org.cmc.music.metadata.MusicMetadata;
import org.cmc.music.metadata.MusicMetadataSet;
import org.cmc.music.myid3.MyID3;

import android.annotation.SuppressLint;
import android.graphics.YuvImage;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.util.Log;

/**
 * @author Administrator
 * Doc tat ca tap tin mp3 va video(mp4, wav, ... ) trong thu muc /mnt/sdcard/
 *  --> roi lay ve thong tin cua tung song (album, artist, genre, length, size ...)
 */
public class MediaPlayerHelper {
	//private static final String MEDIA_PATH = "/mnt/sdcard/";
	
	/*Cac thong tin ve 1 bai hat*/
	private static final String NAME 		= "name";
	private static final String ALBUM		= "album";
	private static final String ARTIST		= "artist";
	private static final String GENRE		= "genre";
	private static final String YEAR		= "year";
	private static final String DURATION	= "duration";
	private static final String PATH		= "path";
	public static final String ARTIST_THUMB_PATH		=	"thumbPath";
	
	//dung rieng cho video
	private static final String FORMAT	=	"format";
	private static final String SIZE	=	"size";
	
	TimeUtilities ultils = new TimeUtilities();
	
	ArrayList<HashMap<String, String>> arrListSongs = new ArrayList<HashMap<String,String>>();
	
	ArrayList<HashMap<String, String>> arrListVideos = new ArrayList<HashMap<String,String>>();
	//constructor
	public MediaPlayerHelper() {
		
	}
	
	
	/**
	 * Lay ve tat cac cac bai hat trong sdcard (thong tin lay ve : ten + path)
	 * @return
	 */
	@SuppressLint("NewApi")
	public List<HashMap<String, String>> getAllSongFromSdCard(String MEDIA_PATH){
		File root = new File(MEDIA_PATH);
		if (root.listFiles() != null) {
			for (File file : root.listFiles()) {
				//neu la file va file .mp3 thi lay
				if (file.isFile() && isMp3File(file.getName().toString()) == true) {
					HashMap<String, String> song = new HashMap<String, String>();
					//put metadata of mp3 file
					//song.put(NAME, file.getName().substring(0, file.getName().length() -4 ));
					//Su dung thu vien MyID3 de lay ve metadata cua file .mp3
					try {
						File newfile = new File(file.getPath());
						
						//dung thu vien MyID3
						MusicMetadataSet metaDataSet = new MyID3().read(newfile);
						MusicMetadata metaData = (MusicMetadata) metaDataSet.getSimplified();
						
						//put Name
						if (metaData.getSongTitle() != null) {
							song.put(NAME, metaData.getSongTitle());
						}else{
							//song.put(NAME, "Unknown Name");
							song.put(NAME, file.getName().substring(0, file.getName().length() -4 ));
						}
						
						//put Album
						if (metaData.getAlbum() != null) {
							song.put(ALBUM, metaData.getAlbum());
						}else{
							song.put(ALBUM, "Unknown Album");
						}
						
						//get Artist of song
						if (metaData.getArtist() != null)  	{
							song.put(ARTIST, metaData.getArtist());
						}else{
							song.put(ARTIST, "Unknown Artist");
						}
						
						//get genre of song
						if (metaData.getGenre() != null)  {
							song.put(GENRE, metaData.getGenre().toString());
						}else{
							song.put(GENRE, "Unknown Genre");
						}
						
						//put year
						if (metaData.getYear() != null) {
							song.put(YEAR, metaData.getYear());
						}else{
							song.put(YEAR, "Unknown Year");
						}
						
						//Lay duration thong qua doi tuong MediaMetadataRetriever
						MediaMetadataRetriever mmr = new MediaMetadataRetriever();
						mmr.setDataSource(file.getPath());
						String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
						//Log.e("Duration :", duration + " **--** ");
						song.put(DURATION, ultils.milliSecondToTimer(Integer.parseInt(duration)));
						
						
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
					//put path
					song.put(PATH, file.getPath());
					song.put(ARTIST_THUMB_PATH, "");
					
					//adding song to arrList
					this.arrListSongs.add(song);
				}//end if file.isFile();
				//Neu gap directory thi duyet tiep (de qui)
				else if (file.isDirectory()) {
					String PATH = MEDIA_PATH + file.getName().toString()+"/";
					getAllSongFromSdCard(PATH);
				}
				
			}
		}
		
		return this.arrListSongs;
	}
	
	
	/**
	 * Kiem tra 1 file xem co phai la file .mp3 hay khong?
	 * @param fileName
	 * @return
	 */
	private Boolean isMp3File(String fileName){
		Boolean isFile = false;
		String[] str = fileName.split("\\.");
		if (str[str.length-1].equals("mp3") || str[str.length-1].equals("MP3")) {
			isFile = true;
		}
		return isFile;
	}
	
	
	
	//Filter files which having .mp3 extension
	class FileExtensionFilter implements FilenameFilter{

		@Override
		public boolean accept(File dir, String filename) {
			// TODO Auto-generated method stub
			return (filename.endsWith(".mp3") || filename.endsWith(".MP3"));
		}
		
	}



	@SuppressLint("NewApi")
	public ArrayList<HashMap<String, String>> getAllVideoFromSdCard(String mediaPath) {
		File root = new File(mediaPath);
		if (root.listFiles() != null) {
			for (File file : root.listFiles()) {
				//neu la file va file dinh dang video thi lay
				if (file.isFile() && isVideoFile(file.getName().toString()) == true) {
					HashMap<String, String> video = new HashMap<String, String>();
					
					//su dung MediaMetadataRetriever de lay ve cac thong tin cua video
					MediaMetadataRetriever mmr = new MediaMetadataRetriever();
					mmr.setDataSource(file.getPath());
					
					//get title
					if (mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE) != null) {
						video.put(NAME,mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE) );
					}else{
						video.put(NAME, file.getName().substring(0, file.getName().length() -4 ));
					}
					
					//get artist
					if (mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST) != null) {
						video.put(ARTIST, mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
					}else{
						video.put(ARTIST, "Unknown Artist");
					}
					
					//get duration
					video.put(DURATION, ultils.milliSecondToTimer(Integer.parseInt( mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION))));
					
					//get size
					video.put(SIZE,"" + getSizeFile(file));
					
					//put path
					video.put(PATH, file.getPath());
					
					//get format
					video.put(FORMAT, getExtension(file.getPath()));
					
					//adding song to arrList
					this.arrListVideos.add(video);
				}//end if file.isFile();
				else if (file.isDirectory()) {//Neu gap directory thi duyet tiep (de qui)
					String PATH = mediaPath + file.getName().toString()+"/";
					getAllVideoFromSdCard(PATH);
				}
			}
		}
		return this.arrListVideos;
	}
	
	
	private String getSizeFile(File file) {
		String size = "";
		long length = file.length()/1024; //--> ra kb
		if (length < 1204) {
			size = size + (int)length + "Kb";
		}else{
			size = size + length/1024 + "M";
		}
		
		return size;
	}


	private Boolean isVideoFile(String fileName){
		Boolean isVideo = false;
		String[] str = fileName.split("\\.");
		String extension = str[str.length-1];
		if (extension.equals("mp4") || extension.equals("MP4") || extension.equals("3gp") || extension.equals("3GP")) {
			isVideo = true;
		}
		
		return isVideo;
	}
	
	private String getExtension(String filepath){
		String[] str = filepath.split("\\.");
		String extension = str[str.length-1];
		return extension;
	}
}
